/* Copyright (c) 2009, Enric Rodriguez (enrodri86@gmail.com)
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 	- Redistributions of source code must retain the above copyright
 * 	notice,	this list of conditions and the following disclaimer.
 * 	- Redistributions in binary form must reproduce the above copyright
 * 	notice, this list of conditions and the following disclaimer in the
 * 	documentation and/or other materials provided with the distribution.
 * 	- Neither the name of the <ORGANIZATION> nor the names of its
 * 	contributors may be used to endorse or promote products derived from
 * 	this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package es.enrodri86.mmo.auth.client.gui;

import es.enrodri86.mmo.auth.client.AudioPlay;
import es.enrodri86.mmo.auth.client.AuthConnection;
import es.enrodri86.mmo.auth.shared.Captcha;
import es.enrodri86.mmo.auth.shared.LoginException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import sun.swing.ImageIconUIResource;

/**
 *
 * @author  enrodri86
 */
public class LoginFrame extends javax.swing.JInternalFrame {
    private ImageIcon imageCaptcha;
    private AudioInputStream ais;
    private AuthConnection ac;
    private MainTest mt;

    /** Creates new form LoginFrame */
    public LoginFrame() {
        initComponents();
        captchaNameLabel.setVisible(false);
        captchaLabel.setVisible(false);
        audioButton.setVisible(false);

        imageCaptchaField.setVisible(false);
        imageCaptchaLabel.setVisible(false);
        audioCaptchaField.setVisible(false);
        audioCaptchaLabel.setVisible(false);

    }

    public void setAuthConnection(AuthConnection ac){
        this.ac = ac;
    }

    public void setMainTest(MainTest mt){
        this.mt = mt;
    }

    public void setCaptcha(Captcha c){
        if(c.isVisualCaptcha()){
            imageCaptcha = new ImageIcon(c.getVisualCaptcha());
            captchaNameLabel.setVisible(true);
            captchaLabel.setVisible(true);
            captchaLabel.setIcon(imageCaptcha);
            audioButton.setVisible(true);
            audioButton.setEnabled(false);
            imageCaptchaField.setVisible(true);
            imageCaptchaLabel.setText(c.getVisualCaptchaQuestion());
            imageCaptchaLabel.setVisible(true);
            pack();
        }

        if(c.isAudioCaptcha()){
            try {
                ais = AudioSystem.getAudioInputStream(new ByteArrayInputStream(c.getAudioCaptcha()));
                captchaNameLabel.setVisible(true);
                audioButton.setVisible(true);
                audioButton.setEnabled(true);
                audioButton.setIcon(new ImageIcon(LoginFrame.class.getResource("sound.png")));
                audioCaptchaField.setVisible(true);
                audioCaptchaLabel.setText(c.getAudioCaptchaQuestion());
                audioCaptchaLabel.setVisible(true);
            } catch (UnsupportedAudioFileException ex) {
                Logger.getLogger(LoginFrame.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(LoginFrame.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                try {
                    ais.close();
                } catch (IOException ex) {
                    Logger.getLogger(LoginFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

        }




    }

    public String getUserField(){
        return userField.getText();
    }

    public char[] getPassField(){
        return passField.getPassword();
    }

    public String getCaptchaField(){
        if(imageCaptcha != null && imageCaptchaField != null && !imageCaptchaField.getText().equals("")){
            return imageCaptchaField.getText();
        }
        if(ais != null && audioCaptchaField != null && !audioCaptchaField.getText().equals("")){
            return audioCaptchaField.getText();
        }
        return "";
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        userField = new javax.swing.JTextField();
        passField = new javax.swing.JPasswordField();
        captchaNameLabel = new javax.swing.JLabel();
        audioButton = new javax.swing.JButton();
        captchaLabel = new javax.swing.JLabel();
        imageCaptchaLabel = new javax.swing.JLabel();
        imageCaptchaField = new javax.swing.JTextField();
        audioCaptchaLabel = new javax.swing.JLabel();
        audioCaptchaField = new javax.swing.JTextField();
        jButton2 = new javax.swing.JButton();

        setTitle("Log On");

        jLabel1.setText("User name:");

        jLabel2.setText("Password:");

        passField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                passFieldActionPerformed(evt);
            }
        });

        captchaNameLabel.setText("Code:");

        audioButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/es/enrodri86/mmo/auth/client/gui/sound_mute.png"))); // NOI18N
        audioButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                audioButtonActionPerformed(evt);
            }
        });

        captchaLabel.setText(" ");

        imageCaptchaLabel.setText("Insert code in image:");

        audioCaptchaLabel.setText("Insert code in audio:");

        jButton2.setText("LOG ON");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(audioButton)
                    .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(captchaNameLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(imageCaptchaLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(audioCaptchaLabel)
                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(audioCaptchaField)
                    .addComponent(imageCaptchaField)
                    .addComponent(captchaLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(passField, javax.swing.GroupLayout.DEFAULT_SIZE, 195, Short.MAX_VALUE)
                    .addComponent(userField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 224, Short.MAX_VALUE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(270, Short.MAX_VALUE)
                .addComponent(jButton2)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(userField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(passField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(captchaNameLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(audioButton))
                    .addComponent(captchaLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 58, Short.MAX_VALUE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(imageCaptchaLabel)
                    .addComponent(imageCaptchaField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(audioCaptchaLabel)
                    .addComponent(audioCaptchaField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton2)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void passFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_passFieldActionPerformed
        // TODO add your handling code here:
}//GEN-LAST:event_passFieldActionPerformed

    private void audioButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_audioButtonActionPerformed
        new AudioPlay(ais).start();
}//GEN-LAST:event_audioButtonActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed

                try {
                    ac.login(getUserField(), getPassField(), getCaptchaField());
                    dispose();
                } catch (LoginException ex) {
                    JOptionPane.showMessageDialog(mt.getDesktopPane(), ex.getDescription(), "Login error!", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                if(ac.isGameSelectionRequired()){
                    GameSelectFrame gsf = new GameSelectFrame();
                    gsf.setAuthConnection(ac);
                    gsf.setMainTest(mt);
                    mt.getDesktopPane().add(gsf);
                    gsf.pack();gsf.setVisible(true);
                }else{
                    ServerSelectFrame gsf = new ServerSelectFrame();
                    gsf.setAuthConnection(ac);
                    gsf.setMainTest(mt);
                    mt.getDesktopPane().add(gsf);
                    gsf.pack();gsf.setVisible(true);
                }


    }//GEN-LAST:event_jButton2ActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton audioButton;
    private javax.swing.JTextField audioCaptchaField;
    private javax.swing.JLabel audioCaptchaLabel;
    private javax.swing.JLabel captchaLabel;
    private javax.swing.JLabel captchaNameLabel;
    private javax.swing.JTextField imageCaptchaField;
    private javax.swing.JLabel imageCaptchaLabel;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPasswordField passField;
    private javax.swing.JTextField userField;
    // End of variables declaration//GEN-END:variables

}
